package com.mjk.common.util;

import com.mjk.common.tools.logger.BizLogger;
import groovy.lang.GroovyClassLoader;
import org.springframework.util.ResourceUtils;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileWriter;
import java.nio.file.Files;

/**
 * Created by majianghua on 2022/11/22.
 */
public class CompileUtil {
    private Class<?> getGroovyClazz(String src) {
    	try(
                GroovyClassLoader groovyClassLoader = new GroovyClassLoader()
        ) {

            return  groovyClassLoader.parseClass(src);
    	}catch(Exception e) {
            BizLogger.error(e);
        }
    	return null;
    }

    public static Class getJdkClazz(String src) {
        String clazzName=getClassNameBySrc(src);
        String packageName = getPackageNameBySrc(src);
        File file = null;
        try{
            String filePath = ResourceUtils.getURL("classpath:").getPath();
            filePath = filePath +packageName.replace(".", "/")+"//";
            if (new File(filePath + clazzName+".class").exists()) {
                return Class.forName(packageName+"."+clazzName);
            }
            File folder = new File(filePath);
            if (!folder.exists() && !folder.isDirectory()) {
                folder.mkdirs();
            }
            file = new File(filePath +"//"+ clazzName+".java");
            Files.delete(file.toPath());
        }catch(Exception e){
            return null;
        }
        try( FileWriter writer =new FileWriter(file);) {
            writer.write(src);
            writer.flush();
            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            StandardJavaFileManager manager = compiler.getStandardFileManager(null, null, null);
            Iterable<? extends JavaFileObject> iterable = manager.getJavaFileObjects(file);
            JavaCompiler.CompilationTask task = compiler.getTask(null, manager, null, null, null, iterable);
            task.call();
            manager.close();
            Class<?> dictModela = CompileUtil.class.getClassLoader().loadClass( packageName+"."+clazzName);
            Files.delete(file.toPath());
            return dictModela;
        } catch (Exception e) {
        	BizLogger.error(e);
        }
        return null;
    }

    private static String getPackageNameBySrc(String src) {
        String start="package";
        String end=";";
        return src.substring(src.indexOf(start)+start.length(),src.indexOf(end)).trim();
    }

    private static String getClassNameBySrc(String src) {
        String start="class";
        String end="{";
        return src.substring(src.indexOf(start)+start.length(),src.indexOf(end)).trim();
    }
}
